﻿using ProjectGamer.DataModels;
using ProjectGamer.Web.DbAdapters.Adapters;
using ProjectGamer.Web.DbAdapters.IAdapters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using ProjectGamer.Web.Models;
using System.Web.Http.Results;


namespace ProjectGamer.Web.Controllers
{
    public class GameController : ApiController
    {
        IGameAdapter _adapter = new GameAdapter();
        //public IHttpActionResult get(int id1, int id2)
        //{
        //    int numOfUsers = _adapter.GetUserCount(id1, id2);
        //    return Ok(numOfUsers);
        //}
        //public IHttpActionResult Get(string search)
        //{
        //    List<Models.GameDetailVM> games = _adapter.GetSearchedGames(search);
        //    return Ok(games);
        //}
        //GET api/game
        public IHttpActionResult Get()
        {
            List<Models.GameDetailVM> games = _adapter.GetAllGames();
            return Ok(games);
        }
        //GET api/game/:id
        [ActionName("available")]
        public IHttpActionResult Get(int id)
        {
            string userid = User.Identity.GetUserId();
            List<Models.GameDetailVM> gamedetail = _adapter.GetGame(id, userid);
            return Ok(gamedetail);
        }
        //GET api/game/user/:id
        [ActionName("user")]
        public IHttpActionResult Get1(string id)
        {
            List<Models.GameDetailVM> rentals = _adapter.GetAllGamesForOwner(id);
            return Ok(rentals);

            //return Unauthorized();
        }
        //POST api/game
        public IHttpActionResult Post([FromBody] Game game)
        {
            if (User.Identity.IsAuthenticated)
            {
                game.ApplicationUserId = User.Identity.GetUserId();
                game = _adapter.AddGame(game);
                return Ok(game);
            }

            return Unauthorized();
        }
        //PUT api/game
        public IHttpActionResult Put([FromBody] Game game)
        {
            if (_adapter.GetUserId(game.Id) == User.Identity.GetUserId())
            {
                game = _adapter.UpdateGame(game);
                return Ok(game);
            }
            return Unauthorized();
        }
        //DELETE api/game/:id
        public IHttpActionResult Delete(int id)
        {
            if (_adapter.GetUserId(id) == User.Identity.GetUserId())
            {
                bool wasDeleted = _adapter.DeleteGame(id);
                if (wasDeleted)
                {
                    return Ok();
                }
            }
            return Unauthorized();
        }
    }
}
